/**
* @CopyRight xinweitech.cn
* @author wuyahui
* @E-mail wuyahui0124505@163.com
* @version 1.0.0
* @Date  2015年4月3日 下午1:03:40
*/
package com.tstudy.laoshibang.profile;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EFragment;
import org.androidannotations.annotations.ViewById;
import org.apache.http.Header;

import com.tstudy.laoshibang.R;
import com.tstudy.laoshibang.base.BaseActivity;
import com.tstudy.laoshibang.base.BaseApplication;
import com.tstudy.laoshibang.base.CONSTANT;
import com.tstudy.laoshibang.base.HttpManager;
import com.tstudy.laoshibang.login.NeedLoginFragment;
import com.tstudy.laoshibang.mode.response.BaseResponse;
import com.tstudy.laoshibang.utils.CommonUtil;
import com.tstudy.laoshibang.utils.LogUtil;
import com.umeng.update.UmengUpdateAgent;
import com.umeng.update.UmengUpdateListener;
import com.umeng.update.UpdateResponse;
import com.umeng.update.UpdateStatus;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
@EFragment(R.layout.setting)
public class SettingFragment extends NeedLoginFragment{
	final static String TAG = "setting";
	public SettingFragment() {
		super();
	}
	
	
	@ViewById(R.id.setting_root)
	RelativeLayout mRootLayout;
	
	@ViewById(R.id.setting_push_switch)
	ImageView mPushSwitch;
	
	@ViewById(R.id.setting_check_version_value)
	TextView mVersionValue;
	
	String mContent;
	String mEmail;
	
	
	boolean mIsFirstLoad = true;
	Handler mHandler;
	LayoutInflater mInflater;

	public static void add(int containerViewId) {
		Bundle args = new Bundle();
		args.putInt(CONSTANT.ARGS.FRAGMENT_ID, containerViewId);
		Fragment fragment = Fragment.instantiate(BaseApplication.mContext,SettingFragment_.class.getName(),args);
		((BaseActivity) BaseApplication.mCurrentActivity).add(containerViewId, fragment, TAG);
	}
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		mHandler = new Handler();
		super.onCreate(savedInstanceState);
	}
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		mInflater = inflater;
		super.onCreateView(inflater, container, savedInstanceState);
		LogUtil.d("--mBaseLayout==" + mRootLayout);
		mIsFirstLoad = mRootLayout == null;
		if (mRootLayout != null) {
			((ViewGroup) mRootLayout.getParent()).removeAllViews();
		}
		return mRootLayout;
	}
	
	@AfterViews
	public void initView(){
		if (mIsFirstLoad) {
			mRootLayout.setOnClickListener(null);
			mPushSwitch.setSelected(true);
			mVersionValue.setText(CommonUtil.getVersion());
		}
	}
	
	@Click({R.id.setting_back,R.id.setting_cache,R.id.setting_check_version_layout,R.id.setting_change_password,R.id.setting_logout,R.id.setting_push_switch})
	public void actionClick(View view){
		switch (view.getId()) {
		case R.id.setting_back:
			backAction(mFragmentId);
			break;
		case R.id.setting_cache:
			String title = BaseApplication.getResString(R.string.setting_cache);
			String content = BaseApplication.getResString(R.string.setting_clear_cache_tip);
			showClearCacheDialog(title, content);
			break;
		case R.id.setting_change_password:
			ModifyPasswordFragment.add(mFragmentId);
			break;
		case R.id.setting_check_version_layout:
			update();
			break;
		case R.id.setting_push_switch:
			view.setSelected(!view.isSelected());
			break;
		case R.id.setting_logout:
			String logoutTitle = BaseApplication.getResString(R.string.logout_dialog_title);
			String logoutContent = BaseApplication.getResString(R.string.logout_dialog_content);
			showLogoutDialog(logoutTitle, logoutContent);
			break;
		default:
			break;
		}
	}
	
	 private void update() {
	        UmengUpdateAgent.setUpdateListener(new UmengUpdateListener() {
	            @Override
	            public void onUpdateReturned(int updateStatus, UpdateResponse updateInfo) {
	                switch (updateStatus) {
	                    case UpdateStatus.Yes: // has update
	                        UmengUpdateAgent.showUpdateDialog(getActivity(), updateInfo);
	                        break;
	                    case UpdateStatus.No: // has no update
	                    	BaseActivity activity = (BaseActivity)getActivity();
	                    	if(activity != null && activity.mFragmentStack.size() > 0){
	                    		BaseApplication.showToast(R.string.setting_latest_version);
	                    	}
	                        break;
	                    case UpdateStatus.NoneWifi: // none wifi
	                        Toast.makeText(BaseApplication.mContext, "没有wifi连接， 只在wifi下更新", Toast.LENGTH_SHORT).show();
	                        break;
	                    case UpdateStatus.Timeout: // time out
	                        Toast.makeText(BaseApplication.mContext, "超时", Toast.LENGTH_SHORT).show();
	                        break;
	                }
	            }
	        });
	        UmengUpdateAgent.update(getActivity());
	    }
	 
	 Dialog mClearCacheDialog;
		@SuppressLint("InflateParams")
		public void showClearCacheDialog(String title,String content){
			RelativeLayout dialogView = (RelativeLayout) mInflater.inflate(R.layout.common_alert_dialog, null);
			if(mClearCacheDialog != null && mClearCacheDialog.isShowing()){
				return;
			}
			mClearCacheDialog = buildAlertDialog(dialogView,CommonUtil.dip2px(80));
			TextView titleTxt = (TextView) dialogView.findViewById(R.id.common_alert_dialog_title);
			final TextView contentTxt = (TextView) dialogView.findViewById(R.id.common_alert_dialog_content);
			TextView cancelTxt = (TextView) dialogView.findViewById(R.id.common_alert_dialog_cancel);
			TextView confirmTxt = (TextView) dialogView.findViewById(R.id.common_alert_dialog_confirm);
			confirmTxt.setText(R.string.common_confirm);
			titleTxt.setText(title);
			contentTxt.setText(content);
			confirmTxt.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					mClearCacheDialog.dismiss();
					HttpManager.getInstance().clearImageCache();
				}
			});
			cancelTxt.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					mClearCacheDialog.dismiss();
				}
			});
			mClearCacheDialog.show();
		}
		
	Dialog mLogoutDialog;
	@SuppressLint("InflateParams")
	public void showLogoutDialog(String title,String content){
		RelativeLayout dialogView = (RelativeLayout) mInflater.inflate(R.layout.common_alert_dialog, null);
		if(mLogoutDialog != null && mLogoutDialog.isShowing()){
			return;
		}
		mLogoutDialog = buildAlertDialog(dialogView,CommonUtil.dip2px(80));
		TextView titleTxt = (TextView) dialogView.findViewById(R.id.common_alert_dialog_title);
		final TextView contentTxt = (TextView) dialogView.findViewById(R.id.common_alert_dialog_content);
		TextView cancelTxt = (TextView) dialogView.findViewById(R.id.common_alert_dialog_cancel);
		TextView confirmTxt = (TextView) dialogView.findViewById(R.id.common_alert_dialog_confirm);
		confirmTxt.setText(R.string.common_confirm);
		titleTxt.setText(title);
		contentTxt.setText(content);
		confirmTxt.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				mLogoutDialog.dismiss();
				logout();
			}
		});
		cancelTxt.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				mLogoutDialog.dismiss();
			}
		});
		mLogoutDialog.show();
	}
	
	public void logout(){
		BaseJsonHandler<BaseResponse> response = new BaseJsonHandler<BaseResponse>() {
			@Override
			public void onStart() {
				showProgressDialog("", "注销...", 0);
				super.onStart();
			}
			@Override
			public void onSuccess(int statusCode, Header[] headers,
					String rawJsonResponse, BaseResponse response) {
				super.onSuccess(statusCode, headers, rawJsonResponse, response);
				if (CommonUtil.responseSuccess(response)) {
					((BaseActivity)getActivity()).logout();
				}else {
                    BaseApplication.showToast(response.getErrMsg());
                }
			}
			@Override
			protected BaseResponse parseResponse(String rawJsonData, boolean isFailure)
					throws Throwable {
				return mGson.fromJson(rawJsonData,BaseResponse.class);
			}
		};
		HttpManager.getInstance().bindPush(false, response);
	}
	
	
	@Override
	public void clear() {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void initArgs(Bundle args) {
		if (args != null) {
			mFragmentId = args.getInt(CONSTANT.ARGS.FRAGMENT_ID);
		}
	}

}
